package com.example.hblog.module.controller;

import com.example.hblog.Result;
import com.example.hblog.module.pojo.Blog;
import com.example.hblog.module.pojo.Image;
import com.example.hblog.module.service.BlogService;
import com.example.hblog.module.service.ImageService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("api")
public class BlogController {

    @Autowired
    private ImageService imageService;
    @Autowired
    private BlogService blogService;
    @Value("${photo.dir}")
    private String realPath;


    @PostMapping("/createUUID")
    public Result createUUID(){
        try{
            String id = (UUID.randomUUID()+"").replace("-","");
            return new Result(200,"生成编号成功",id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"生成编号失败",null);
        }
    }

    /*发布博客*/
    @PostMapping("/addBlog")
    public Result addBlog(@RequestBody Blog blog){
        try{
            System.out.println(blog.getId());
            Date date=new Date();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            blog.setTime(dateFormat.format(date));
            blogService.addBlog(blog);
            return new Result(200,"发布成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"发布失败",null);

        }
    }

    @ResponseBody
    @GetMapping("/allBlog")
    public List<Blog> allBlogs() {
        return blogService.allBlog();
    }

    /*根据id查询博客*/
    @ResponseBody
    @GetMapping("/showBlog")
    public Blog showBlog(String id){
        log.info("查看新闻的id: [{}]",id);
        return blogService.showBlog(id);
    }

    /**
     * 分页请求
     * @param currentPage 当前页
     * @param pageSize  每页显示大小
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getBlogList/{currentPage}/{pageSize}",method = RequestMethod.GET)
    public PageInfo<Blog> getBlogByBlogPage(@PathVariable(name = "currentPage") int currentPage, @PathVariable(name = "pageSize") int pageSize){
        return blogService.getAllUsersByPage(currentPage,pageSize);
    }

    @ResponseBody
    @RequestMapping(value = "getSearchList/{currentPage}/{pageSize}",method = RequestMethod.GET)
    public PageInfo<Blog> getSearchList(@PathVariable(name = "currentPage") int currentPage, @PathVariable(name = "pageSize") int pageSize,String title){
        return blogService.getSearchPage(currentPage,pageSize,title);
    }

    /*根据title查询博客*/
    @ResponseBody
    @GetMapping("/searchBlog")
    public List<Blog> searchBlog(String title){
        log.info("title=>: [{}]",title);
        return blogService.searchBlog(title);
    }

    /*编辑博客*/
    @PostMapping("/editorBlog")
    public Result editorBlog(@RequestBody Blog blog){
        try{
            blogService.editorBlog(blog);
            return new Result(200,"编辑成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"编辑失败",null);

        }
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file,Image image ,HttpServletRequest request)throws Exception {
        try{
            //图片保存
            String fileName = file.getOriginalFilename();
            String newFileName= UUID.randomUUID().toString()+"."+ FilenameUtils.getExtension(file.getOriginalFilename());//获取文件名后缀
            file.transferTo(new File(realPath,newFileName));
            image.setImage(newFileName);
            imageService.addImg(image);
//            //设置图片地址
//            imageService.addImg(newFileName);
            String fileUrl="http://120.77.71.211:9011/";
            //文件获取路径
            fileUrl = fileUrl + request.getContextPath()  + newFileName;
            return new Result(200,"上传成功",fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"上传失败",null);
        }
    }

    /*删除图片*/
    @PostMapping("/deleteImage")
    public Result deleteImage(String url){
        System.out.println(url);
        String newUrl = url.substring(26);

        log.info(newUrl);
        log.info(realPath);
        try{
            imageService.deleteimgNow(newUrl);
            File file=new File(realPath,newUrl);
            if(file.exists())file.delete();//删除图片
            return new Result(200,"删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"删除失败",null);
        }

    }

    /*删除博客*/
    @PostMapping("/deleteBlog")
    public Result deleteBlog(@RequestBody  Blog blog){
        try {
            List<Image> images = imageService.findImgByID(blog.getId());
            if (images.size()>0){
                for (int i=0; i<images.size();i++){
                    File file=new File(realPath,images.get(i).getImage());
                    if(file.exists())file.delete();
                }
            }
            blogService.deleteBlog(blog.getId());
            imageService.deleteimg(blog.getId());
            return new Result(200,"删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"删除失败",null);
        }
    }

}
